package groovyhelper;

import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.ActionManager;

import java.util.Map;
import java.util.HashMap;

import org.jetbrains.annotations.NotNull;

public class GroovyHelper implements ApplicationComponent {
    private Logger logger = Logger.getInstance(getClass().getName());
    private Map<String, AnAction> oldActions = new HashMap<String, AnAction>();
    public GroovyHelper() {
    }

    public void initComponent() {
        ActionManager instance = ActionManager.getInstance();
        overrideAction(instance, "CommentByLineComment", new GroovyCommentByLineCommentAction());
        overrideAction(instance, "CommentByBlockComment", new GroovyCommentByBlockCommentAction());
        overrideAction(instance, "CodeCompletion", new GroovyCodeCompletionAction());
    }

    private void overrideAction(ActionManager amgr, String actionId, GroovyBaseOverrideAction newAction) {
        AnAction existingAction = amgr.getAction(actionId);
        newAction.setDelegate(existingAction);
        amgr.unregisterAction(actionId);
        amgr.registerAction(actionId, newAction);
        oldActions.put(actionId, existingAction);
    }

    public void disposeComponent() {
        ActionManager amgr = ActionManager.getInstance();
        for (Object o : oldActions.keySet()) {
            String actionName = (String) o;
            AnAction existingAction = oldActions.get(actionName);
            amgr.unregisterAction(actionName);
            amgr.registerAction(actionName, existingAction);
        }
    }

    @NotNull
    public String getComponentName() {
        return "GroovyHelper";
    }
}
